package com.dbflow5.provider;

import com.dbflow5.config.FlowManager;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.database.FlowCursor;
import com.dbflow5.query.OperatorGroup;
import com.dbflow5.structure.BaseModel;
import ohos.aafwk.ability.DataAbilityRemoteException;

/**
 * Description: Provides a base implementation of a [Model] backed
 * by a content provider. All model operations are overridden using the [ContentUtils].
 * Consider using a [BaseSyncableProviderModel] if you wish to
 * keep modifications locally from the [ContentProvider]
 */
public abstract class BaseProviderModel extends BaseModel implements ModelProvider {

    public BaseProviderModel() {
        super();
    }

    @Override
    public boolean save(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        int count = ContentUtils.update(FlowManager.contentResolver(), updateUri(), this);
        if (count == 0) {
            return insert(wrapper) > 0;
        } else {
            return count > 0;
        }
    }

    @Override
    public boolean delete(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        return ContentUtils.delete(FlowManager.contentResolver(), deleteUri(), this) > 0;
    }

    @Override
    public boolean update(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        return ContentUtils.update(FlowManager.contentResolver(), updateUri(), this) > 0;
    }

    @Override
    public long insert(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        return ContentUtils.insert(FlowManager.contentResolver(), insertUri(), this);
    }

    @Override
    public boolean exists(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        FlowCursor cursor = ContentUtils.query(FlowManager.contentResolver(),
                queryUri(), modelAdapter.getPrimaryConditionClause(this), "");
        boolean exists = cursor != null && cursor.getRowCount() > 0;
        if(cursor != null) {
            cursor.close();
        }
        return exists;
    }

    @Override
    public <T> T load(OperatorGroup whereOperatorGroup, String orderBy, DatabaseWrapper wrapper, String... columns) throws DataAbilityRemoteException {
        FlowCursor cursor = ContentUtils.query(FlowManager.contentResolver(),
                queryUri(), whereOperatorGroup, orderBy, columns);

        if(cursor != null) {
            if (cursor.goToFirstRow()) {
                return (T)modelAdapter.loadFromCursor(cursor, wrapper);
            }
        }
        return null;
    }

    @Override
    public <T> T load(DatabaseWrapper databaseWrapper) throws DataAbilityRemoteException {
        return (T)load(modelAdapter.getPrimaryConditionClause(this), "", databaseWrapper);
    }
}
